import csv

year_begin = 1960
population = {}
with open('data/population/API_SP.POP.TOTL_DS2_en_csv_v2_4770387.csv', newline='', encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=',', quotechar='"')
    for row in reader:
        population[row['Country Code']] = tuple(int(x) for x in list(row.values())[1:])
# print(population)

# csv_list = os.listdir('data/tmp')
# year_available = []
# for file in csv_list:
#     first = True
#     year_available.clear()
#     with open(f'data/tmp/{file}', newline='') as csvfile:
#         csvfile.readline()
#         content = list(csv.DictReader(csvfile, delimiter=',', quotechar='"'))[:-2]
#         for row in content:
#             country = row.pop('ISO')
#             row.pop('Country')
#             if first:
#                 first = False
#                 for key in row:
#                     if row[key]:
#                         year_available.append(int(key))
#                 print(year_available)
#             print(row.values())

with open(f'data/empty-lines-deleted/1.1.csv', newline='', encoding='utf-8') as csvfile:
    content = list(csv.DictReader(csvfile, delimiter=',', quotechar='"'))
    head = list(content[0].keys())
    begin, end = int(head[2]), int(head[-1])
    if end > 2021:
        end = 2021
    year_available = list(range(begin, end + 1))

    result = {}
    for row in content:
        country = row.pop('ISO')
        row.pop('Country')
        result[country] = tuple(float(x) for x in row.values())
    avg = [0] * (end - begin + 1)
    for year in year_available:
        total_population = 0
        for country in result:
            total_population += population[country][year - year_begin]
        for country in result:
            avg[year - begin] += result[country][year - begin] * population[country][year - year_begin] / total_population
print(avg)
